#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tile import *
from hexspace import *
import pygame
from pygame.locals import *

import sys; sys.path.insert(0, "..")
import pygl2d
import string

"""
    Used to create both stellar maps and ship maps
"""

class board:   
    def __init__(self,filename,players):
        self.currentPlayer = players[0]
        self.players = players
        self.modified = False # If the board is modified, the minimap use this variable to rebuild itself
        self.background =pygame.image.load("data/img/background/cieletoile.png")# pygl2d.image.Image("data/img/background/cieletoile.png");
        
        self.width = 0 # in number of Hexs
        self.height = 0 # in number of Hexs
        self.hexs = [] # Hexs of the board
        if type("") == type(filename):
            self.load(filename)
        else:
            self.new(filename) # In this case filename contains the size => (w,h)
        self.carac = {}

    def __hex2key(self,h):
        return "%d-%s-%d" % (h.type,h.skin,h.pos)

    def new(self,size):
        self.hexs = []
        self.width,self.height = size
        for j in range(self.height):
            for i in range(self.width):
                self.hexs.append(emptyHex((i,j),0,None,self.players))
    
    def save(self,filename):
        hexstypes2num = {}
        i=0
        for h in self.hexs:
            key = self.__hex2key(h)
            if not key in hexstypes2num.keys():
                hexstypes2num[key]=i
                i+=1

        f=open(filename,'w')
        i=0
        for ht in hexstypes2num.keys():
            line = "%d = %s\n" % (hexstypes2num[ht],ht)
            f.write(line)
            i+=1

        f.write("\n")
        f.write("MAP %dx%d\n" % (self.width,self.height))

        i = 0
        line = ""
        for h in self.hexs:
            i+=1
            key = self.__hex2key(h)
            line+="%d " % hexstypes2num[key]
            if i % self.width == 0:
                line += "\n"
                f.write(line)
                line = ""
            
            
        f.write(line)
        f.close()
        
    def load(self,filename):
        self.modified = True
        self.filename = filename
        self.hexs = []
        variables = {}
        startmap = False
        j = 0
        f = open(filename)
        l = f.readline()
        
        while len(l)>0:
            l=l.replace("\n","").replace("\r","")
            if l.find("#")>=0:
                l=l.split('#')[0]
                
            if l.find("=")>=0:
                l = l.replace(" ","")
                name,content = l.split("=")
                variables[name]=content.replace("\n","").replace("\r","");
		
            elif startmap:
                ids = l.split(" ")
                if "" in ids:
                    ids.remove("")
                i=0
                for hid in ids:
                    if len(hid)==0:
                        continue
                    else:
                        hexvalues = variables[hid]
                        hextype,hexskin,hexangle = hexvalues.split("-")
                        hextype = int(hextype)
                        hexangle = int(hexangle)
                        hexConstruct = dictType2hexConst[hextype]
                        if hexConstruct!=None:
                            if hexskin=="None":
                                hexskin = None
                            self.hexs.append(hexConstruct((i,j),hexangle,hexskin,self.players))
                        i+=1
                j+=1
                
            elif l.startswith("MAP"):
                l = l[3:].replace(" ","")
                w,h = l.split("x")
                self.width = int(w)
                self.height = int(h)
                startmap=True    
            l = f.readline()
        f.close()
        self.carac = variables


    def dbgprint(self):
        print self.filename
        #for j in range(self.height):
        #    line = ""
        #    for i in range(self.width):
        #        line+="%d " % self.hexs[i+j*self.width].type
        #    print line

    def draw(self):
        for hexspace in self.hexs:
            hexspace.draw()
        #for hexspace in self.hexs:
        #    hexspace.drawInfos()

    def drawSubPart(self,xi,yi,xf,yf):
        todraw=[]
    
        for i in range(xi,xf+1):
            #if i % 2 == 0:
                
     
            for j in range(yi ,yf+1):
                todraw.append(self.hexs[i+j*self.width])

        j = yi - 1
        if j >= 0 :
            for i in range(xi,xf+1):
                todraw.append(self.hexs[i+j*self.width])
                
        j = yf + 1
        if j < self.height  :
            for i in range(xi,xf+1):
                if i % 2 == 0:
                    todraw.append(self.hexs[i+j*self.width])
        i = xi - 1
        if i > 0:
            for j in range(yi ,yf+1):
                todraw.append(self.hexs[i+j*self.width])

            #i = xf + 1
            #if i < self.width:
            #    for j in range(yi ,yf+1):
            #        todraw.append(self.hexs[i+j*self.width])
            
        
        for hexspace in todraw:
            hexspace.draw(-xi,-yi)
        for hexspace in todraw:
            hexspace.drawInfos(-xi,-yi)

    

    def getHex(self,x,y):
        if x < 0 or x >= self.width or y < 0 or y >=self.height:
            return None
        return self.hexs[x+self.width*y]

    def isModified(self):
        if self.modified:
            self.modified = False
            return True
        return False
    
    def setHex(self,hexa):
        x,y = hexa.getCoord()
        if x == None or y == None:
            return
        if x+self.width*y < self.width*self.height:
            prevHex = self.hexs[x + self.width * y]
            if not prevHex.isGlobFlag(OUTOFBOARD):
                self.hexs[x + self.width * y] = hexa
                self.modified = True

    def getNeighbourHex(self,x,y):
        neighbours = []
        if x % 2 == 0:
            neighboursTmpCoords = [(x,y-1),(x-1,y-1),(x-1,y),(x,y+1),(x+1,y),(x+1,y-1)]
        else:
            neighboursTmpCoords = [(x,y-1),(x-1,y),(x-1,y+1),(x,y+1),(x+1,y+1),(x+1,y)]

        for x1,y1 in neighboursTmpCoords:
            if x1 >= 0 and x1 <self.width and y1>=0 and y1<self.height:
                neighbours.append(self.getHex(x1,y1))
                
            else:
                neighbours.append(None)
                
        return neighbours

    def getNeighbourHexPos(self,coord,pos):
        x,y = coord
        if x % 2 == 0:
            xo,yo = Pos2NeighbourEven[pos]
        else:
            xo,yo = Pos2NeighbourOdd[pos]

        return self.getHex(x+xo,y+yo)
    

    def getPassableNeighbours(self,x,y):
        neighbours = self.getNeighbourHex(x,y)
        currHex = self.getHex(x,y)
        passableNeighbours = []
        for border in currHex.getPassable():
            
            if neighbours[border] != None:
                if getOppositePos(border) in neighbours[border].getPassable():
                    
                    passableNeighbours.append(neighbours[border])
                    
        return passableNeighbours    

    def setCurrentPlayer(self,currPlayer):
        self.currentPlayer = currPlayer
        for h in self.hexs:
            h.setCurrentPlayer(currPlayer)

    def setPlayers(self,players):
        self.players = players

    def getPlayers(self):
        return self.players


# Test of a ship board

if __name__ == "__main__":
    from gui import *
    from gameinit import *
    from player import *
    player = "player1" #TODO Use a player Class instead of a string
    players = [player]
    
    ship = board("data/shipmaps/shiptest2.txt",players)
    ship.setCurrentPlayer(player)
    x=4
    y=3
    hexs = ship.getNeighbourHex(x,y)
    hexspass = ship.getPassableNeighbours(x,y)
    
    h = ship.getHex(x,y)
    h.select(player)
    for h in hexs:
        if h!=None:
            h.highlight(player)

    for h in hexspass:
        if h!=None:
            h.select(player)
    
    vstep = Tile.vstep
    hstep = Tile.hstep
    
    clock = pygame.time.Clock()
    running = 1
    pygl2d.window.begin_draw()  
       
        #ship.draw()
    ship.drawSubPart(0,0,10,8)

    pygl2d.window.end_draw()
    pygame.display.flip()
    
    while running:
        clock.tick(120.0)
        pygame.display.set_caption(str(int(clock.get_fps())))

        pygl2d.window.begin_draw()  
       
        #ship.draw()
        ship.drawSubPart(0,0,10,8)

        pygl2d.window.end_draw()
            
            
        
        for e in pygame.event.get():
            if e.type == QUIT:
                running = 0
            if e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    running = 0
        

    pygame.quit()
    
